<template>
  <basic-container>
    <avue-crud :option="option"
               :table-loading="loading"
               :data="data"
               v-model:page="page"
               :permission="permissionList"
               :before-open="beforeOpen"
               v-model="form"
               ref="crud"
               @row-update="rowUpdate"
               @row-save="rowSave"
               @row-del="rowDel"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @on-load="onLoad">
      <template #menu-left>
        <el-button type="danger"
                   icon="el-icon-delete"
                   plain
                   v-if="permission.push_template_delete"
                   @click="handleDelete">删 除
        </el-button>
      </template>
      <template #menu="{row,index,size}">
        <el-button text
                   type="primary"
                   icon="el-icon-connection"
                   @click="debug(row,index)">
          调试
        </el-button>
      </template>
    </avue-crud>
    <el-dialog v-model="visibleDebug" :before-close="beforeCloseDebug" title="消息调试" width="600">
      <el-row>
        <el-alert
            title="消息调试功能，用于调试消息模版，请输入 Json格式 参数调试，与模版参数对应。"
            type="info" :closable="false"/>
      </el-row>
      <el-row>
        <avue-form ref="form" v-model="debugForm" :option="debugOption" @submit="handleDebug"/>
      </el-row>
    </el-dialog>
  </basic-container>
</template>

<script>
import {getList, getDetail, add, update, remove, debug} from "@/api/iot/push/template";
import {mapGetters} from "vuex";

export default {
  data() {
    return {
      debugForm: {},
      form: {},
      query: {},
      loading: true,
      visibleDebug: false,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      option: {
        height: 'auto',
        calcHeight: 32,
        searchShow: true,
        searchMenuSpan: 6,
        tip: false,
        border: true,
        index: true,
        viewBtn: true,
        selection: true,
        menuWidth: 280,
        labelWidth: 120,
        searchLabelWidth: 120,
        dialogWidth: 600,
        column: [
          {
            label: "模版名称",
            prop: "templateName",
            width: 280,
            search: true,
            span: 24,
            rules: [{
              required: true,
              message: "请输入模版名称",
              trigger: "blur"
            }]
          },
          {
            label: "模版编号",
            labelTip: "用于快速自动调用推送服务的唯一编号",
            prop: "templateCode",
            width: 100,
            search: true,
            span: 24,
            rules: [{
              required: true,
              message: "请输入模版编号",
              trigger: "blur"
            }]
          },
          {
            label: "绑定渠道",
            labelTip: "渠道配置指定的不同配置参数",
            prop: "channelId",
            type: "select",
            dicUrl: "/blade-iot/push/channel/select",
            props: {
              label: "pushName",
              value: "id",
              desc: "pushTypeName",
            },
            width: 150,
            search: true,
            span: 24,
            rules: [{
              required: true,
              message: "请选择绑定渠道",
              trigger: "blur"
            }]
          },
          {
            label: "模版内容",
            labelTip: "模版内容支持${}与#{}占位符接受参数,短信则输入平台发放的模版ID",
            prop: "templateParam",
            type: "textarea",
            minRows: 6,
            span: 24,
            rules: [{
              required: true,
              message: "请输入模版内容,短信则输入模版ID",
              trigger: "blur"
            }]
          },
          {
            label: "模版备注",
            prop: "templateDesc",
            type: "textarea",
            width: 150,
            minRows: 2,
            span: 24
          },
        ]
      },
      debugOption: {
        column: [
          {
            label: "模版名称",
            prop: "templateName",
            disabled: true,
            span: 24,
          },
          {
            label: "模版编号",
            prop: "templateCode",
            disabled: true,
            span: 24,
          },
          {
            label: "绑定渠道",
            prop: "channelId",
            type: "select",
            dicUrl: "/blade-iot/push/channel/select",
            props: {
              label: "pushName",
              value: "id",
              desc: "pushTypeName",
            },
            disabled: true,
            span: 24,
          },
          {
            label: "模版内容",
            prop: "templateParam",
            type: "textarea",
            disabled: true,
            minRows: 6,
            span: 24,
          },
          {
            label: "调试内容",
            prop: "debugParam",
            type: "textarea",
            minRows: 6,
            span: 24,
          },
        ]
      },
      data: []
    };
  },
  computed: {
    ...mapGetters(["permission"]),
    permissionList() {
      return {
        addBtn: this.validData(this.permission.push_template_add, false),
        viewBtn: this.validData(this.permission.push_template_view, false),
        delBtn: this.validData(this.permission.push_template_delete, false),
        editBtn: this.validData(this.permission.push_template_edit, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(",");
    }
  },
  methods: {
    debug(row) {
      this.debugForm = row;
      this.visibleDebug = true;
    },
    beforeCloseDebug() {
      this.visibleDebug = false;
    },
    handleDebug(form, done, loading) {
      debug(form.templateCode, form.debugParam).then(() => {
        this.$message({
          type: "success",
          message: "调试完毕,请查看推送消息!"
        });
        this.visibleDebug = false;
      }, error => {
        window.console.log(error);
      });
      done();
    },
    rowSave(row, done, loading) {
      add(row).then(() => {
        done();
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
      }, error => {
        window.console.log(error);
        loading();
      });
    },
    rowUpdate(row, index, done, loading) {
      update(row).then(() => {
        done();
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
      }, error => {
        window.console.log(error);
        loading();
      });
    },
    rowDel(row) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
          .then(() => {
            return remove(row.id);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          });
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
          .then(() => {
            return remove(this.ids);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.$refs.crud.toggleSelection();
          });
    },
    beforeOpen(done, type) {
      if (["edit", "view"].includes(type)) {
        getDetail(this.form.id).then(res => {
          this.form = res.data.data;
        });
      }
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    }
  }
};
</script>

<style>
</style>
